import './reportChart/style/index.less';
import React from 'react';
import {inject, observer} from 'mobx-react';
import {routerShape} from 'react-router';
import {WeaEchart, WeaRightMenu, WeaTop, WeaLeftRightLayout,WeaNewScroll,WeaSelect,WeaDialog,WeaTools,WeaLocaleProvider} from 'ecCom';
import {Button,Popover,message} from 'antd';
import CollapsePanel from './CollapsePanel';
import { WeaTableNew } from 'comsMobx';
import * as API from '../../apis/customReportForm';
import PublicTable from './PublicTable';

const { TableStore } = WeaTableNew;
const WeaTable = WeaTableNew.WeaTable;

let tableStore = new TableStore();
let tableStoreDetail = new TableStore();

import CardItem from './reportChart/CardItem';
import {downloadCvs2Img} from '../../util/reportUtil';
import {getLineOption,getBarOption,getPieOption,getFunnelOption,getRadarOption} from './util/getChartOption';

let _this;
const getLabel = WeaLocaleProvider.getLabel;

@inject('wfViewReportStore')
@observer

export default class Main extends React.Component {

    static contextTypes = {
        router: routerShape
    }

    constructor(props) {
        super(props);
        _this = this;
        const chartType  = this.init();
        this.state = {
            type : 'line1',
            chartType : chartType,
            chartActive : [0,0],   //记录当前选中的图形，用于标记颜色。第一项表示主图形菜单中顺序，第二项表示子图形菜单中顺序。
            tableType : 0,    //记录下面折叠table。0为总数据的，1为详细数据。
            dataReadable : [],   //ture 为可见，false
            countInit : false,   //初始化筛选条件和数值条件的条数
            conditionCount : 0,   //筛选条件的可见条数
            formulaCount : [],  //数值条件的可见条数的formula数组
            allDatas : [],
        }
    }

    //初始化所有支持的图表

    init(){
        const chartType = [];
        chartType.push({
            type:'line',
            iconsrc:'/images/ecology9/workflow/line1.png',
            title: getLabel(384596,'折线图'),
            arrName:[getLabel(384597,'基础折线图'),getLabel(384599,'面积折线图'),getLabel(384600,'分段折线图')],
            arrSrc:['/images/ecology9/workflow/line1.png','/images/ecology9/workflow/line2.png','/images/ecology9/workflow/line3.png'],
            arrType:['line1','line2','line3']
        });
        chartType.push({
            type:'bar',
            iconsrc:'/images/ecology9/workflow/bar1.png',
            title: getLabel(384602,'柱状图'),
            arrName:[getLabel(384604,'基础柱状图'),getLabel(384606,'组成柱状图'),getLabel(384607,'堆叠条形图')],
            arrSrc:['/images/ecology9/workflow/bar1.png','/images/ecology9/workflow/bar2.png','/images/ecology9/workflow/bar4.png'],
            arrType:['bar1','bar2','bar4']
        });
        chartType.push({
            type:'pie',
            iconsrc:'/images/ecology9/workflow/pie3.png',
            title: getLabel(384609,'饼图'),
            arrName:[getLabel(384611,'基础饼图'),getLabel(384612,'圆环图')],
            arrSrc:['/images/ecology9/workflow/pie3.png','/images/ecology9/workflow/pie2.png'],
            arrType:['pie3','pie2']
        });
        chartType.push({
            type:'funnel',
            iconsrc:'/images/ecology9/workflow/funnel1.png',
            title: getLabel(384613,'漏斗图'),
            arrName:[getLabel(384614,'基础漏斗图')],
            arrSrc:['/images/ecology9/workflow/funnel1.png'],
            arrType:['funnel1']
        });
        chartType.push({
            type:'radar',
            iconsrc:'/images/ecology9/workflow/radar1.png',
            title: getLabel(384616,'雷达图'),
            arrName:[getLabel(384617,'基础雷达图')],
            arrSrc:['/images/ecology9/workflow/radar1.png'],
            arrType:['radar1']
        });
        // chartType.push({type:'map',iconsrc:'/images/ecology9/workflow/map1.png',title:'地图',arrName:1});
        return chartType;
    }

    getContent (key) {
        // falg 标记是哪一种图形 ，0：折线图，1：柱状图，2：饼图，3：漏斗图，4：雷达图，5：地图，6：热力图
        const {chartType = [],chartActive} = this.state;
        const chartConfig = chartType[key];
        let content = '';
        if(chartConfig)  {
            const {arrName = [] ,type = '',title = '',arrSrc = [],arrType= []} =  chartConfig;
            let subChartConfigs = [];
            for (let i = 0; i < arrName.length; i++) {
                subChartConfigs.push({
                    key:`${arrType[i]}`,
                    iconsrc : `${arrSrc[i]}`,
                    title : `${arrName[i]}`
                })
            }
            let ulHeigth  =  subChartConfigs.length > 2 ? '400px':`${subChartConfigs.length*160 + 40}px`;
            content = (
                <div style={{height:'100%',overflow:'auto'}}>
                    <ul className="subUl" style={{background:'#fff',padding:'20px 0px',height:ulHeigth}}>
                        {
                            subChartConfigs.map((item,index)=>{
                                return (
                                    <li style={{textAlign: 'center',padding:'0px 12px'}} onClick={()=>this.setState({type:item.key,chartActive:[key,index]})}>
                                        <CardItem ecId={`${this && this.props && this.props.ecId || ''}_CardItem@99c4bt@${index}`} active={index === chartActive[1] && key === chartActive[0]} item={item} />
                                    </li>
                                )
                            })
                        }
                    </ul>
                </div>

            );
        }
        return content;
    }

    getPosition (node) {
        let top = node.offsetTop;
        let left = node.offsetLeft;
        let parent = node.offsetParent;
        while(parent != null) {
            top += parent.offsetTop;
            left += parent.offsetLeft;
            parent = parent.offsetParent;
        }
        return {left,top};
    }

    componentDidMount () {
        //获得table的数据
        const sessionkey = this.props.location.query.sessionkey;
        tableStore.getDatas(sessionkey, 1);

        API.getChartAllData({tableKey:sessionkey}).then(data => {
          if(data.datas) {
            this.setState({allDatas:[...data.datas]})
          }
        })

    }

    componentDidUpdate (preProps, preState) {
        const {type,dataReadable} = this.state;
        if(type !== preState.type || dataReadable !== preState.dataReadable) {
            if(this.myChart && preState.countInit){
                this.myChart.clear();
                this.myChart.paint();
            }
        }
    }

    componentWillUnmount () {
        tableStore = new TableStore();
    }
    echartReady (status) {
        if(status === 'ready') {
            let timer = setTimeout(()=>{
                this.myChart.resize();
            },100);

        }
    }

    getOption(type = 'line1') {

        const {dataReadable,allDatas,formulaCount} = this.state;

        if(formulaCount.length === 0){
            message.warning(getLabel(383656,'数据不能生成图表！'));
            return {};
        }

        const {columns = []} = tableStore;

        const legend = [];
        const legendKey = [];
        const columnLegend = [];
        const xAxisData = [];
        let seriesData = [];
        const xlabelKey = [];
        let lindex  = 0;

        columns.map((col,index)=>{
            const {dataIndex = '',title = ''} = col;
            if(dataReadable[index]) {

               let count = 0;
               for (let i = 0; i < formulaCount.length; i++){
                   if (formulaCount[i] === dataIndex) {
                       legendKey.push(dataIndex);
                       legend.push(title);
                       columnLegend.push({key:lindex,showname:title});
                       lindex++;
                       break;
                   } else {
                       count++;
                   }
               }
               if(count === formulaCount.length){
                   if(dataIndex.indexOf('formula') < 0) {
                       xlabelKey.push(dataIndex);
                   }
               }

                // if (dataIndex !== 'requestids' && dataIndex.indexOf('randomField') < 0) {
                //     if(dataIndex.indexOf('formula') === -1) {
                //         xlabelKey.push(dataIndex);
                //     } else {
                //         legendKey.push(dataIndex);
                //         legend.push(title);
                //         columnLegend.push({key:lindex,showname:title});
                //         lindex++;
                //     }
                // }
            }
        });

        allDatas.map((coldata) =>{
            let labelname  = '';
            xlabelKey.map((key) => {
                let val  = coldata[`${key}span`];
                labelname =  labelname == '' ? val:`${labelname}/${val}`;
            });

            xAxisData.push(labelname);

            legendKey.map((key,i) => {
                if(seriesData.length > i) {
                    const itemdata  = seriesData[i];
                    const {data = []} = itemdata;
                    data.push(coldata[`${key}`]);
                } else {
                    const data  = [];
                    data.push(coldata[`${key}`]);
                    const itemdata  = {
                        name: legend[i],
                        data: data
                    };
                    seriesData.push(itemdata);
                }
            });

        });

        let option;

        if (type === 'line1' || type === '') {
            option = getLineOption('line1',{seriesData,xAxisData,legend});
        } else if (type === 'line2') {
            option = getLineOption('line2',{seriesData,xAxisData,legend});
        } else if (type === 'line3') {
            option = getLineOption('line3',{seriesData,xAxisData,legend});
        } else if (type === 'line4') {
            option = getLineOption('line4',{seriesData,xAxisData,legend});
        }

        if (type === 'bar1') {
            option = getBarOption('bar1',{seriesData,xAxisData,legend});

        } else if (type === 'bar2') {
            option = getBarOption('bar2',{seriesData,xAxisData,legend});
        } else if (type === 'bar4') {
            option = getBarOption('bar4', {seriesData, xAxisData, legend});
        }

        if (type === 'pie3') {
            option = getPieOption('pie3', {seriesData,xAxisData,legend});
        } else if (type === 'pie2') {
            option = getPieOption('pie2', {seriesData,xAxisData,legend});
        }
        if (type === 'funnel1') {
            option = getFunnelOption('funnel1', {seriesData,xAxisData,legend});
        }
        if (type === 'radar1') {
            option = getRadarOption('radar1', {seriesData,xAxisData,legend});

        }

        return option;
    }

    chartAction(chart) {
        chart.off("click");
        chart.on('click', (params) => {
            // console.log("params", params);
            // _this.collapse.toggleCollapse(true);
        });
    }

    picSaveAs() {
        let canvasDom = jQuery('canvas')[0];
        const title = this.props.location.query.title||'';
        const src = canvasDom.toDataURL("image/jpg");
        let value = src.substring(src.indexOf(',') + 1);

        // downloadCvs2Img(canvasDom)

        WeaTools.downloadFile('/api/ec/dev/util/exportBase64', "POST", {src: value});

    }

    downloadHtml() {

        const {type} = this.state;
        const title = this.props.location.query.title||'';

        let html = ` <!DOCTYPE html>
        <html style="height: 100%">
            <head>
            <meta charset="utf-8">
            </head>
            <body style="height: 100%; margin: 0">
            
                <div id="container" style="height: 90%; width: 90%; margin :20px auto"></div>
                
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/echarts.min.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts-gl/echarts-gl.min.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts-stat/ecStat.min.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/extension/dataTool.min.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/china.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/map/js/world.js"></script>
                <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=ZUONbpqGBsYGXNIYHicvbAbM"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/echarts/extension/bmap.min.js"></script>
                <script type="text/javascript" src="http://echarts.baidu.com/gallery/vendors/simplex.js"></script>
                
                <script type="text/javascript">
                    let dom = document.getElementById("container");
                    let myChart = echarts.init(dom);
                    let option = ${JSON.stringify(this.getOption(type),null,4)};
                    if (option && typeof option === "object") {
                        myChart.setOption(option, true);
                    }
                    
                </script>
            </body>
        </html>`;




        // let myWin = window.open('about:blank');
        // myWin.document.write(html);
        //
        //
        //
        // this.download('http://baidu.com','aaa.html')


        if (navigator.appVersion.toString().indexOf('.NET') > 0){
            window.navigator.msSaveBlob(html, `${title}.html`);
        } else {
            let file = new Blob([html], {
                type: 'text/html;charset=UTF-8',
                encoding: 'UTF-8'
            });

            let a = document.createElement('a');
            a.href = URL.createObjectURL(file);
            a.download = `${title}.html`;
            a.click();
        }

    }


    getBlob(url) {
        return new Promise(resolve => {
            const xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = () => {
                if (xhr.status === 200) {
                    resolve(xhr.response);
                }
            };

            xhr.send();
        });
    }

    saveAsHTML(blob, filename) {
        if (window.navigator.msSaveOrOpenBlob) {
            navigator.msSaveBlob(blob, filename);
        } else {
            const link = document.createElement('a');

            link.href = window.URL.createObjectURL(blob);
            link.download = filename;
            link.click();

            window.URL.revokeObjectURL(link.href);
        }
    }

    download(url, filename) {
        this.getBlob(url).then(blob => {
            this.saveAsHTML(blob, filename);
        });
    }


    getButtons() {
        let btns = [];
        btns.push(
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@tgkboa@picSaveAs`} type="primary" onClick={() => this.picSaveAs()}>{getLabel(383666,'图片另存为')}</Button>),
            (<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@x3hcr2@downloadHtml`} type="primary" onClick={() => this.downloadHtml()}>{getLabel(383667,'下载html版')}</Button>),
        );
        return btns;
    }

    dropMenuDatas() {
        let btns = [];
        btns.push(
            {
                key: "1",
                icon: <i className="icon-coms-pic"/>,
                content: getLabel(383666,'图片另存为'),
                onClick: key => {
                    this.picSaveAs()
                }
            },
            {
                key: "2",
                icon: <i className="icon-coms-download"/>,
                content: getLabel(383667,'下载html版'),
                onClick: key => {
                    this.downloadHtml()
                }
            }
        )
        return btns;
    }

    controlLeft (showLeft) {
        let timer = setTimeout(()=>{
            this.myChart.resize();
        },200)
    }

    collapseCallback (v) {
        if(v) {
            let height = jQuery('#chartBox').height() - 200;
            jQuery('#chartBox').height(height);
            this.myChart && this.myChart.resize();
        } else{
            let height = jQuery('#chartBox').height() + 200;
            jQuery('#chartBox').height(height);
            this.myChart && this.myChart.resize();
            // this.setState({tableType:0})
        }
    }

    panelCallback (v) {
        if(!v){
            // this.setState({tableType:1});
        }
    }

    preView () {
        let {sessionkey,...params} = this.props.location.query;
        this.context.router.push({
            pathname : "/main/workflow/viewCustomResult",
            query : {
                ...params
            }
        });
    }

    render() {

        let {type,chartType=[],tableType,chartActive,allDatas,dataReadable} = this.state;
        let {wfViewReportStore} = this.props;
        const title = this.props.location.query.title||'';

        return (
            <div style={{height:'100%'}} className="wf-chart">

                <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@5m7g6k`} datas={this.dropMenuDatas()}>
                    <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@njamsr`}

                        title={<div className="chartTitle"><a onClick={() => this.preView()}>{title}</a>&nbsp;>&nbsp;{getLabel(383664,'生成图表')}</div>}
                        loading={false}
                        icon={<i className="icon-coms-workflow"/>}
                        iconBgcolor="#0079DE"
                        buttons={this.getButtons()}
                        buttonSpace={10}
                        showDropIcon={true}
                        dropMenuDatas={this.dropMenuDatas()}
                    >
                        <WeaLeftRightLayout ecId={`${this && this.props && this.props.ecId || ''}_WeaLeftRightLayout@1eogzm`}
                            isNew={true}
                            onCollapse={showLeft => this.controlLeft(showLeft)}
                            leftWidth={160}
                            leftCom={
                                <WeaNewScroll ecId={`${this && this.props && this.props.ecId || ''}_WeaNewScroll@qsvf3w`} height={'100%'}>
                                    <ul id="mainId" className="wf-custom-report-chart-left-icon">
                                        {
                                            chartType.map((item,index)=>{
                                                return (
                                                    <Popover ecId={`${this && this.props && this.props.ecId || ''}_Popover@f2kdfu@${index}`} arrowPointAtCenter={true} overlayClassName="wf-custom-report-popover" content={this.getContent(index)} placement="rightTop" trigger="click">
                                                        <li className="myLis">
                                                            <CardItem ecId={`${this && this.props && this.props.ecId || ''}_CardItem@jgdvt0@${index}`} active={index === chartActive[0]} item={item}/>
                                                        </li>
                                                    </Popover>
                                                )
                                            })
                                        }
                                    </ul>
                                </WeaNewScroll>
                            }
                        >

                            <div style={{height:'100%',overflow:'auto'}}>
                                <div id="chartBox" style={{width:'calc(100% - 60px)',height:'calc(100% - 60px)',paddingTop:'10px',margin:'0 auto'}}>
                                    {
                                        tableStore.columns.length > 0 && allDatas.length > 0 && dataReadable.length > 0 &&
                                        <WeaEchart ecId={`${this && this.props && this.props.ecId || ''}_WeaEchart@6j8sry`}
                                            ref={echart => {
                                                this.myChart = echart
                                            }}
                                            chartName=""
                                            useDefault={false}
                                            option={this.getOption(type)}
                                            chartAction={this.chartAction}
                                            onStatusChange={status => this.echartReady(status)}
                                        />
                                    }

                                </div>

                                <CollapsePanel ecId={`${this && this.props && this.props.ecId || ''}_CollapsePanel@a3fg5y`}
                                    ref={(collapse)=>{this.collapse = collapse}}
                                    collapseCallback={(v)=>this.collapseCallback(v)}
                                    panelCallback={(v)=>this.panelCallback(v)}
                                    className="collapseBox" height="245px"
                                >
                                    {
                                        tableType === 0 && tableStore.dataKey.length > 0 &&
                                        <PublicTable ecId={`${this && this.props && this.props.ecId || ''}_PublicTable@dgc4x4`}
                                            tableStore={tableStore}
                                            getColumns={(columns) => this.getColumns(columns)}
                                        />
                                    }
                                    {
                                        tableType !== 0 &&
                                        <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@r28lqn`}
                                            comsWeaTableStore={tableStoreDetail}
                                            hasOrder={true}
                                            needScroll={true}
                                            scroll={{y:155}}
                                        />
                                    }

                                </CollapsePanel>
                            </div>

                        </WeaLeftRightLayout>
                    </WeaTop>
                </WeaRightMenu>
            </div>
        );
    }

    getColumns(columns) {

        let {allDatas} = this.state;

        if(columns && allDatas.length > 0 && columns.length > 0){

            let {allDatas} = this.state;

            let legendKey = [];  //记录formula
            let seriesData = []; //记录可生成坐标的值

            columns.map((col,index)=>{
                const {dataIndex = '',title = ''} = col;
                    if (dataIndex !== 'requestids' && dataIndex.indexOf('randomField') < 0) {
                        if(dataIndex.indexOf('formula') > -1) {
                            legendKey.push(dataIndex);
                            // legend.push(title);
                        }
                    }
            });

            allDatas.map((coldata) =>{
                legendKey.map((key,i) => {
                    if(seriesData.length > i) {
                        const itemdata  = seriesData[i];
                        const {data = []} = itemdata;
                        data.push(coldata[`${key}`]);
                    } else {
                        const data  = [];
                        data.push(coldata[`${key}`]);
                        const itemdata  = {
                            name: key,
                            data: data
                        };
                        seriesData.push(itemdata);
                    }
                });

            });

            legendKey = []; //记录可生成左边的formula

            let temp = [...seriesData];
            temp.map((item,index)=>{
                legendKey.push(item.name);
                for(let i = 0; i < item.data.length; i++){
                    if(isNaN(item.data[i])) {
                        seriesData.splice(index,1);
                        legendKey.pop();
                        break;
                    }
                }

            });

            let {dataReadable,conditionCount,formulaCount,countInit} = _this.state;

            let newConditionCount = [], newDataReadable = [];

            let newColumns = columns.map((item,index)=>{
                if (item.dataIndex !== "requestids" && item.dataIndex.indexOf('randomField') === -1) {

                    if(!countInit){
                        let count = 0;
                        for (let i = 0; i < legendKey.length; i++){
                            if(legendKey[i] === item.dataIndex) {
                                break ;
                            }else{
                                count++;
                            }
                        }

                        if(count === seriesData.length) {
                            newConditionCount.push(item.dataIndex);
                        }
                        newDataReadable[index] = true;
                    }

                    for (let i = 0; i < legendKey.length; i++) {
                        const description = dataReadable[index] ? getLabel(384591,"点击隐藏此列") : getLabel(384593,"点击显示此列");
                        if (legendKey[i] === item.dataIndex) {
                            item.title = <div style={{display:'inline-block'}}>
                                <span style={{verticalAlign:'middle'}}>{item.title}</span>
                                <i title={description} onClick={()=>{
                                    if(!dataReadable[index]) {
                                        if (item.dataIndex.indexOf('formula') > -1) {
                                            let newArr = [...dataReadable];
                                            newArr[index] = !dataReadable[index];
                                            formulaCount.push(legendKey[i])
                                            _this.setState({dataReadable:newArr,formulaCount:[...formulaCount]});
                                        }
                                    } else {
                                        if(item.dataIndex.indexOf('formula') > -1){
                                            if(formulaCount.length === 1){
                                                message.info(getLabel(383668,'至少显示一列'));
                                            }else{
                                                let newArr = [...dataReadable];
                                                newArr[index] = !dataReadable[index];
                                                let temp = [...formulaCount];
                                                temp.map((item,index)=>{
                                                    if(item === legendKey[i]) {
                                                        formulaCount.splice(index,1);
                                                    }
                                                })
                                                _this.setState({dataReadable:newArr,formulaCount:[...formulaCount]});
                                            }
                                        }
                                    }
                                }} className={dataReadable[index] ? "icon-coms-display titleIcon" : "icon-coms-hide titleIconHide"}
                                />
                            </div>;
                            break ;
                        }
                    }
                }
                return item;
            });

            !countInit && _this.setState({countInit:true,conditionCount:[...newConditionCount],formulaCount:[...legendKey],dataReadable:[...newDataReadable]});

            // newColumns = newColumns.map(column => {
            //     let newColumn = column;
            //     let lastdata = {};
            //     newColumn.render = (text, record, index) => {
            //         const {dataIndex = ''} = newColumn;
            //         if(dataIndex === 'requestids') {
            //             return (<a style={{color:'#4D7AD8'}} onClick={_this.showReqList.bind(_this,text)}>查看</a>);
            //         }else if(!dataIndex.startsWith('formula')) {
            //             const tempdate  = lastdata[dataIndex];
            //             if( index > 0 && tempdate == text) {
            //                 return "";
            //             } else  {
            //                 lastdata[dataIndex] = text;
            //                 return  record[`${dataIndex}span`] ;
            //             }
            //         } else {
            //             return record[`${dataIndex}span`];
            //         }
            //     }
            // });
        }
    }

}

